const {url,dbname,collections} = require("./config")
const { MongoClient, ObjectId} = require("mongodb")

// function getCollection(collectionName) {
//     return new Promise((resolve,reject)=>{
//         MongoClient.connect(url,function (err, db) {
//             if (err) {
//                 reject(err)
//             }else{
//                 resolve({
//                     collection: db.db(dbname).collection(collectionName),
//                     db
//                     })
//             }
//         }
//     )
//     })
// }
function getCollection(collectionName) {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                reject(err);
            } else {
                resolve({
                    collection: db.db(dbname).collection(collectionName),
                    db,
                });
            }
        });
    });
}

function callback({ db, resolve, reject }, { res, err }) {
    console.log("db callback:res/err=",res,err);
    db.close();
    if (err) {
        reject(err);
    } else {
        resolve(res);
    }
}

// 添加商品
function execCreate(collectionName, content) {
    return new Promise(async (resolve, reject) => {
        try {
            const { collection, db } = await getCollection(collectionName);
            collection.insertMany(content, function (err, res) {
                callback({ db, resolve, reject }, { res, err });
            });
        } catch (err) {
            reject(err);
        }
    });
}

// 注：不传的参数，需要设置默认值
function execRetrieve(collectionName,whereOption={},{skip,limit}={}) {

    return new Promise((resolve,reject)=>{
        MongoClient.connect(url,function (err, db) {
            if (err) {
                console.log(url);
                reject(err)
            }else{
                const dbo = db.db(dbname);
                let data = dbo.collection(collectionName).find(whereOption)

                    if(skip && limit){
                        data.skip(skip).limit(limit)
                    }

                    data.toArray(function (err, result) {
                        
                        db.close();
                        if(err){
                            reject(err)
                        }else{
                            resolve(result)
                        }
                    });
            }
        }
    )
    })
}

// 修改/更新
function execUpdate(collectionName, id, content) {
    return new Promise(async (resolve, reject) => {
        try {
            const { collection, db } = await getCollection(collectionName);
            collection.updateOne(
                { _id: ObjectId(id) },
                {$set:content},
                function (err, res) {
                    callback({ db, resolve, reject }, { res, err });
                }
            );
        } catch (err) {
            // console.log("err=",err);
            reject(err);
        }
    });
}

// 删除商品
function execDelete(collectionName, id) {
    return new Promise(async (resolve, reject) => {
        try {
            const { collection, db } = await getCollection(collectionName);
            collection.deleteOne({ _id: ObjectId(id) }, function (err, obj) {
                db.close();
                if (err) {
                    reject(err);
                } else {
                    resolve({ msg: "删除文档成功" });
                }
            });
        } catch (err) {
            reject(err);
        }
    });
}

module.exports = {
    execCreate,
    execRetrieve,
    execDelete,
    execUpdate,
};